<template>
	<view>
		<view class="page__content">
			<z-paging ref="paging" :refresher-only="true" :fixed="false" @query="getPageInfo">
				<template #top>
					<up-navbar class="head-index" :fixed="false" :safeAreaInsetTop="true" titleStyle="color:#fff"
						:autoBack="true" leftIconColor="#fff" title="统计">
						<template #right>
							<up-subsection style="min-width: 100px;" :list="pageConfig.changeTypeList"
								:current="pageConfig.curNow" @change="sectionChange"></up-subsection>
						</template>
					</up-navbar>

					<!-- 时间选择器 -->
					<view class="example-body">
						<uni-datetime-picker v-model="pageConfig.singleTimes" @change="changeDate" type="daterange"
							:end="pageConfig.EndDate" rangeSeparator="至"></uni-datetime-picker>
					</view>

					<view style="background-color: #51d0d0;">
						<up-tabs :list="pageConfig.tabList" :current="pageConfig.tabsIndex" @change="changeTab"
							lineColor="#fff" :activeStyle="{'font-size':'24px','font-weight': '600'}"></up-tabs>
					</view>
				</template>


				<view class="page__content__main">
					<view class="charts-box">
						<qiun-data-charts type="line" :opts="pageConfig.opts" :chartData="pageConfig.chartData"
							:ontouch="true"></qiun-data-charts>
					</view>

					<view class="charts-box x-bc">
						<view style="flex: 1;">
							<qiun-data-charts type="pie" :opts="pageConfig.opts_pie"
								:chartData="pageConfig.chartData_pie"></qiun-data-charts>
						</view>
						<view v-if="pageConfig.chartData_pie.series.length" class="x-c"
							style="width: 200px;border-left: 2px solid #f9f9f9;height: 100%;font-size: 14px;">
							<view>
								<view v-for="(item,index) in pageConfig.chartData_pie.series[0].data" :key="index"
									style="margin-bottom: 20rpx;font-weight: 600;"
									:style="{color: pageConfig.opts_pie.color[index]}">
									<text style="margin-right: 8px;">{{item.name}}:</text>
									<text>{{item.value}}</text>
								</view>
							</view>
						</view>
					</view>

					<view class="x-sec" style="width: 100%;height: 100px;background-color: #fff;padding: 10px 0;">
						<view v-for="(item,index) in pageConfig.BottomList" :key="index" class="y-f"
							style="flex: 1;margin: 0 4px;height: 100%;background-color: #f9f9f9;justify-content: center;">

							<view class="x-c">
								<text style="font-size: 24px;font-weight: 600;"
									:style="{color:item.IconColor || '#333'}">{{item.Nums}}</text>
								<text style="font-size: 12px;margin-left: 4px;">{{item.Unit}}</text>
							</view>
							<view class="x-c" style="margin-top: 10px;">
								<text style="font-size: 14px;">{{item.Text}}</text>
							</view>
						</view>

					</view>


				</view>


			</z-paging>
		</view>

	</view>
</template>

<script setup lang="ts">
	import { reactive, computed, onMounted, ref, nextTick, getCurrentInstance, watch } from 'vue'
	import { onLoad, onShow, onUnload } from '@dcloudio/uni-app'
	import { useMainStore, useQmsStore, usePermissionStore, useUserStore, useBluetoothStore } from '@/store';
	const qmsStore = useQmsStore();
	const mainStore = useMainStore();
	const permissionStore = usePermissionStore();
	const userStore = useUserStore();
	const bluetoothStore = useBluetoothStore();
	import useRequestQueue from '@/uni_modules/mc-ui/libs/http/UniversalRequestQueue';
	const { request, requestByUrl, onAllComplete, onError } = useRequestQueue();


	interface pagingInstance {
		reload : () => void;
		refresh : () => void;
		complete : () => void;
		setLocalPaging : () => void;
	}
	let paging = ref<pagingInstance | any>(null);

	let pageConfig = reactive<any>({
		singleTimes: [],
		EndDate: null,

		changeTypeList: [{ name: '数量' }, { name: '批次' }],
		curNow: 0,

		tabsIndex: 0,
		tabList: [],

		opts: {
			color: ["#91CB74", "#EE6666", "#FAC858", "#1890FF", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4",
				"#ea7ccc"
			],
			padding: [25, 20, 20, 15],
			enableScroll: true,
			legend: {},
			xAxis: {
				disableGrid: true,
				// calibration: true,
				scrollShow: true,
				itemCount: 4,
				// min: 0,
			},
			yAxis: {
				gridType: "dash",
				dashLength: 2,
				data: [{
					calibration: true,
					min: 0,
					// max: 100
				}]
			},
			extra: {
				line: {
					type: "curve",
					width: 2,
					activeType: "hollow"
				}
			}
		},
		chartData: {},

		// 饼图 -- 合格率
		opts_pie: {
			color: ["#42bf44", "#e44a4d", "#4e77ff", "#1890FF", "#73C0DE", "#3CA272", "#FC8452", "#9A60B4", "#ea7ccc"],
			padding: [5, 5, 5, 5],
			enableScroll: false,
			extra: {
				pie: {
					activeOpacity: 0.5,
					activeRadius: 10,
					offsetAngle: 0,
					labelWidth: 15,
					border: true,
					borderWidth: 3,
					borderColor: "#FFFFFF",
					// linearType: "custom"
				}
			}
		},
		chartData_pie: {
			series: []
		},



		AnnularProgress: [], // 环形进度数据

		BottomList: [],

		ShowAnnular: false,
	});

	// 设置限制时间范围

	pageConfig.EndDate = uni.$utils.dateFormat((new Date()).getTime(), 'yyyy-MM-dd')
	// 设置初始化时间
	pageConfig.singleTimes = [
		uni.$utils.dateFormat((new Date()).getTime() - 1000 * 60 * 60 * 24 * 30 * 2, 'yyyy-MM-dd'),
		uni.$utils.dateFormat((new Date()).getTime(), 'yyyy-MM-dd')
	];

	// 环形进度数据重置
	const ResetData = [
		{
			"HGPercentage": 0,
			"HGColor": "#4ADA88",
			"HGText": "合格率",
			"HGID": 0
		}, {
			"HGPercentage": 0,
			"HGColor": "#da4518",
			"HGText": "不合格率",
			"HGID": 1
		}, {
			"HGPercentage": 0,
			"HGColor": "#4e77ff",
			"HGText": "让步放行",
			"HGID": 2
		},
	];

	const initConfig = async () => {

		try {
			// 1、获取 tab 数据
			const ret = await request({
				config: {
				},
				url: 'Get_QMS_FType',
				method: 'POST',
				data: {}
			});

			if (ret.status == 200) {
				let arr = [];
				let obj = {};
				ret.data.ds.forEach((item, index) => {
					arr.push({
						name: item.Name,
						value: item.FType,
						id: index,
					});
					obj[item.FType] = item.Name
				});

				let NData = permissionStore.moduleInfoAll[0]["Node"].filter(item => {
					return !item.IsTabbar;
				})

				arr = arr.filter((item) => {
					let flag = false;
					flag = NData.some((ele) => ele.APFunName == obj[item.value])
					return flag;
				})

				pageConfig.tabList = arr;

				setTimeout(() => {
					getPageInfo()
				}, 500)
			};

		} catch (error) {

			uni.$utils.hideLoading();
			paging.value.endRefresh();
			//TODO handle the exception
		}
	}

	//修改月、天的格式，保持两位数显示
	const add0 = (m : any) => {
		return m < 10 ? '0' + m : m
	}

	/** 根据数组对象中的属性名，重排数组
	 * @param TypeName      数组对象中对比的属性名
	 * @param ChangeList    对比的数组
	 */
	const ChangeList = ['合格率', '不合格率', '让步放行'];
	const customSort = (a, b) => {
		// 获取字符串在数组中的索引
		let indexA = ChangeList.indexOf(a['HGText']);
		let indexB = ChangeList.indexOf(b['HGText']);

		// 比较索引值并返回排序结果
		return indexA - indexB;
	};

	const sectionChange = (index) => {
		if (pageConfig.curNow == index) return;
		uni.$utils.showLoading();
		pageConfig.curNow = index;
		setTimeout(() => {
			getPageInfo();
		}, 500)

	}

	const changeDate = () => {
		changeTab({
			...pageConfig.tabList[pageConfig.tabsIndex],
			index: pageConfig.tabsIndex
		})
	}

	// 切换检验项
	const changeTab = (data : any) => {
		uni.$utils.showLoading();

		// 因为切换Tab无法改变索引，手动记录一下

		pageConfig.tabsIndex = data.index;

		setTimeout(() => {
			getPageInfo();
		}, 500)
	}

	const getPageInfo = async () => {

		try {

			let data = pageConfig.tabList[pageConfig.tabsIndex];

			let parma = {
				FType: data.value, // 检验项
				FBdate: pageConfig.singleTimes[0], // 开始时间
				FEdate: pageConfig.singleTimes[1], // 结束时间
				LX: pageConfig.curNow + 1, // 数量 1 ；批次 2
			};

			const ret_1st = await request({
				config: {
				},
				url: 'JYTJJK',
				method: 'POST',
				data: parma
			});


			if (ret_1st.status == 200) {
				const ret_1st_map = {
					opts: {
						categories: [], // x轴数据
						series: []
					},
					hg: {
						name: '合格数',
						data: []
					},
					bhg: {
						name: '不合格数',
						data: []
					}
				}


				ret_1st.data.ds.forEach((item : any) => {
					ret_1st_map.opts.categories.push(add0(item.DAY))

					ret_1st_map.hg.data.push(item.HGNumber)
					ret_1st_map.bhg.data.push(item.BHGNumber)
				})


				ret_1st_map.opts.series.push(ret_1st_map.hg)
				ret_1st_map.opts.series.push(ret_1st_map.bhg)
				pageConfig.chartData = uni.$utils.deepClone(ret_1st_map.opts);

				const ret_2nd = await request({
					config: {
					},
					url: 'JYTJJK2',
					method: 'POST',
					data: parma
				});


				if (ret_2nd.status == 200) {
					let NewData = JSON.parse(JSON.stringify(ResetData));

					// if (ret_2nd.data.ds.length) {
					//  NewData[0]['HGPercentage'] = ret_2nd.data.ds[0]['HGPercentage']
					//  NewData[1]['HGPercentage'] = ret_2nd.data.ds[0]['BHGPercentage']
					//  NewData[2]['HGPercentage'] = ret_2nd.data.ds[0]['RBFXHGPercentage']
					//  pageConfig.AnnularProgress = NewData.sort(customSort)
					// } else {
					//  pageConfig.AnnularProgress = ResetData.sort(customSort);
					// }

					let chart_pie_info = {
						series: [
							{
								data: [
									{ "name": "合格率", "value": 0 },
									{ "name": "不合格率", "value": 0 },
									// { "name": "让步放行", "value": 0 }
								]
							}
						]
					};


					if (ret_2nd.data.ds.length) {
						chart_pie_info.series[0].data[0]['value'] = ret_2nd.data.ds[0]['HGPercentage']
						chart_pie_info.series[0].data[1]['value'] = ret_2nd.data.ds[0]['BHGPercentage']
						// chart_pie_info.series[0].data[2]['value'] = ret_2nd.data.ds[0]['RBFXHGPercentage']

						if (pageConfig.curNow == 1) {
							chart_pie_info.series[0].data.push({
								"name": "让步放行",
								"value": ret_2nd.data.ds[0]['RBFXHGPercentage']
							})
						}
					} else {
						if (pageConfig.curNow == 1) {
							chart_pie_info.series[0].data.push({
								"name": "让步放行",
								"value": 0
							})
						}
					}
					pageConfig.chartData_pie = chart_pie_info;





					const ret_3rd = await request({
						config: {
						},
						url: 'JYTJJK3',
						method: 'POST',
						data: parma
					});


					if (ret_3rd.status == 200) {
						let ret_3rd_basic_arr = [ // 底部数据组
							{
								Icon: 'share',
								IconColor: '#ffb011',
								Nums: 0,
								Text: '检验数量',
								Unit: '个',
							}, {
								Icon: 'share',
								IconColor: '#da4518',
								Nums: 0,
								Text: '不合格数量',
								Unit: '个',
							}, {
								Icon: 'share',
								IconColor: '#4ADA88',
								Nums: 0,
								Text: '合格数量',
								Unit: '个',
							},
						];

						ret_3rd_basic_arr[0].Nums = ret_3rd.data.ds[0].JYSL;
						ret_3rd_basic_arr[1].Nums = ret_3rd.data.ds[0].BHGSL;
						ret_3rd_basic_arr[2].Nums = ret_3rd.data.ds[0].HGSL;
						if (ret_3rd.data.ds[0].RBCS >= 0) {
							ret_3rd_basic_arr[3] = {
								Icon: 'share',
								IconColor: '#4e77ff',
								Nums: ret_3rd.data.ds[0].RBCS,
								Text: '让步批次',
								Unit: '次',
							}
						};

						if (pageConfig.curNow == 1) {
							ret_3rd_basic_arr[0].Text = '检验批次';
							ret_3rd_basic_arr[1].Text = '不合格批次';
							ret_3rd_basic_arr[2].Text = '合格批次';

							ret_3rd_basic_arr.map(item => {
								item.Unit = '次'
							})
						}

						pageConfig.BottomList = ret_3rd_basic_arr;
						pageConfig.ShowAnnular = true;


						uni.$utils.hideLoading();
						paging.value.endRefresh();
					}

				}
			}

		} catch (error) {
			uni.$utils.hideLoading();
			paging.value.endRefresh();
			//TODO handle the exception
		}
	}

	/**
		 * 过滤数组数据
		 * @param {Array} 过滤数组
		 * @param {Function} 过滤条件
		 * @return {Array} 返回过滤后的数据
		 */
	const getFilterData = (data : any[], filter : (ret : any, ind : any) => boolean) : any[] => {
		return data.filter(filter)
	}

	onLoad(() => {
		initConfig();
	})
</script>

<style lang="scss">
	.page__content {
		height: 100vh;
		background-color: #f9f9f9;

		// 时间
		.example-body {
			padding: 6px 20px;
			color: #fff;
			background-color: #51d0d0;

			.uni-date-editor--x {
				background-color: #fff;
			}
		}

		// Tab页签
		.u-tabs__wrapper__nav {
			color: #fff !important;
			background-color: #51d0d0 !important;

			.u-tabs__wrapper__nav__item__text {
				color: #fff !important;
			}
		}

		.u-tabs__wrapper__nav__item {
			width: fit-content !important;
		}


		&__main {
			padding: 10px;

			.charts-box {
				width: 100%;
				height: 300px;
				background-color: #fff;
				margin-bottom: 10px;
			}

			.AnnularProgressBox {
				display: flex;
				justify-content: space-around;
				align-items: center;
				background-color: #fff;
				margin-top: 10px;

				.progressBox {
					position: relative;
					width: 180rpx;
					height: 180rpx;
					margin: 0 auto;
					margin-top: 33rpx;

					.centerTxt {
						position: absolute;
						top: 50%;
						left: 50%;
						transform: translate(-50%, -50%);

						.num {
							font-size: 22rpx;
							font-family: Arial;
							font-weight: bold;
							// color: #38393A;
						}
					}

					.text {
						font-size: 16px;
						font-family: PingFang SC;
						font-weight: 400;
						// color: #8A8B8B;
						margin-top: 10rpx;
						text-align: center !important;
					}
				}
			}
		}
	}
</style>